/**
 * Created by ZFL on 2018/1/10.
 */
function appInit() {
    PageInit();
}
function PageInit() {
    $(".goods-info textarea").keyup(function () {
        $('.goods-info textarea').val($('.goods-info textarea').val().substr(0,200));
        $(".num").text($('.goods-info textarea').val().length+'/200');
    });

}
//加载评论商品
var app=new Vue({
    el:"#app",
    data:{
        evaluData:{}
    },
    filters:function () {
        //内置过滤器
    },
    mounted:function () {
        this.$nextTick(function () {
            //初始化
            this.cartView();
        });
    },
    methods:{
        cartView:function () {
            if(sessionStorage.getItem('evaData')!=""){
                app.evaluData = JSON.parse(sessionStorage.getItem('evaData'));
            }
        }
    }
});

//提交评论
function submit() {
    if($(".goods-info textarea").val()==""){
        YDUI.dialog.toast('评论不能为空', 'none', function () {});
    }else {
        evaluateGoods();
    }
}
function evaluateGoods() {
    getImgUrl();
    $.ajaxHandler({
        model: function () {
            var obj = {};
            obj.comment=[];
            var objChild={};
            objChild.commentText = $(".goods-info textarea").val();//评论内容
            objChild.goodId = app.evaluData.goodId;
            objChild.image1 =imgUrl[0];
            objChild.image2 = imgUrl[1];
            objChild.image3 = imgUrl[2];
            objChild.specName = app.evaluData.specName;//商品规格组合
            objChild.orderDetailId = app.evaluData.orderDetailId;//订单详情ID
            obj.userId =  com_obj.userId;
            obj.orderInfoId = sessionStorage.getItem("orderInfoId");//子订单ID
            obj.comment.push(objChild);
            console.log(obj)
            return obj;
        },
        visibleTime: 500,
        visible: 'show',
        approve: true,
        api: "yg_baijiaplatform/goodsComment/addGoodsComment",
        success: function (result) {
            //console.log(result);
            if (result.code == 10000) {
                YDUI.dialog.toast('评价成功', 'success', 800, function (){
                    window.location.href='../user/me.html';
                });
            } else {
                YDUI.dialog.toast(result.message, 'error', 800);
            }
        }
    });
}



function getObjectURL(file) {
    var url = null ;
    if (window.createObjectURL!=undefined) {  // basic
        url = window.createObjectURL(file) ;
    } else if (window.URL!=undefined) {       // mozilla(firefox)
        url = window.URL.createObjectURL(file);
    } else if (window.webkitURL!=undefined) { // web_kit or chrome
        url = window.webkitURL.createObjectURL(file) ;
    }
    return url ;
}

function convertImgToBase64(url, callback, outputFormat){
    var canvas = document.createElement('CANVAS');
    var ctx = canvas.getContext('2d');
    var img = new Image;
    quality = 0.6, //image quality
        img.crossOrigin = 'Anonymous';
    img.onload = function(){
        var width = img.width;
        var height = img.height;
        // 按比例压缩4倍
        var rate = (width<height ? width/height:height/width)/4;
        canvas.width = width*rate;
        canvas.height = height*rate;
        ctx.drawImage(img,0,0,width,height,0,0,width*rate,height*rate);

        var dataURL = canvas.toDataURL(outputFormat || 'image/png',quality);
        callback.call(this, dataURL);
        canvas = null;
    };
    img.src = url;
}

$('.uploadImgs').on('change','.showImgWrap input',function(){
    var _this=this;
    var imageUrl=getObjectURL($(this)[0].files[0]);
    convertImgToBase64(imageUrl,function(base64Img){
        // base64转图片不需要base64的前缀data:image/jpg;base64

        suffix=base64Img.split(';')[0].split('/')[1];    //图片后缀
        imgBase=base64Img.split(',')[1];    //base64
        var index=$(_this).parents('.showImgWrap').index();
        uploadIdImgs(suffix,imgBase,index)

    })
})
var urlNumber=0;   //上传图片的数目
//点击删除  删除图片
$('.uploadImgs').on('click','.showImgWrap img',function(){
    var index=$(this).parents('.showImgWrap').index();
    //如果上传三张图片   删除一张后  只剩两张   要保证最后一张是待上传状态   在删除前判断是否已上传三张
    getImgUrl();
    $('.showImgWrap')[index].remove();
    if(urlNumber==3){
        var string=' <div class="showImgWrap"> <div class="showImg"></div><input type="file" accept="image/*"><img src="../images/order/del.png" alt="" class="del"></div>';
        $($('.uploadImgs .showImgWrap')[index-1]).after(string)
    }



})


function uploadIdImgs(suf,base,ind){
    $.ajaxHandler({
        model:function(){
            var obj={};
            obj.catalog=1;
            obj.suffix=suf;
            obj.imgBase=base;
            console.log(obj)
            return obj;
        },
        visibleTime: 0,
        dataType: "json",
        approve: true,
        api: 'yg_baijiaplatform/common/imageBasePath',
        success:function(res){
            if(res.code==10000){
                var data=res.data;
                $($('.uploadImgs .showImg')[ind]).css({
                    'background-image':'url('+data+')'
                });
                $($('.uploadImgs .showImgWrap')[ind]).find('.del').show()


                //当照片数小于等于两个时   能动态加入
                if($('.showImgWrap').length<=2){
                    var string=' <div class="showImgWrap"> <div class="showImg"></div><input type="file" accept="image/*"><img src="../images/order/del.png" alt="" class="del"></div>';
                    $($('.uploadImgs .showImgWrap')[ind]).after(string)
                }

            }else{
                YDUI.dialog.toast(res.message,1000)
            }
        }
    })
}
//

function getImgUrl(){
    imgUrl=[];
    for(var i=0;i<$('.uploadImgs .showImg').length;i++){
        var url=($($('.uploadImgs .showImg')[i]).css('backgroundImage')).split('"')[1];
        if(url.indexOf('submit.png')>0){
            url=''
        }else{
            urlNumber++;
        }

        imgUrl.push(url);
        console.log(urlNumber)

    }
}

//返回上一页
function returnBack() {
    window.history.back();  //返回上一页
}